/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Post;

import DAO.Usuario.HibernateUtil;
import Model.Post;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.commons.codec.binary.Base64;
import org.hibernate.Session;

/**
 *
 * @author pedro
 */
@Path("/postIphone")
public class PostIphone {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public String getCoordenates(Post post) {
        
        String result = null;
        Session session = HibernateUtil.getSession();
        HibernateUtil.beginTransaction();
        try {
            ArrayList<String> lista = (ArrayList<String>) session.createQuery("SELECT P.imagem FROM Post P Where P.cod=?")
                    .setInteger(0, post.getCod())
                    .list();

            session.getTransaction().commit();
            HibernateUtil.commitTransaction();

            if (!lista.isEmpty()) {
                result = encodeImages(lista);
            }
        } catch (Exception e) {
            System.out.println(e);
            result="Error";
            session.getTransaction().rollback();
            
        } finally {
            try {
                HibernateUtil.closeSession();
            } catch (Throwable e) {
                System.out.println(e.getMessage());
            }
        }

        return result;
    }

    public String encodeImages(ArrayList<String> posts) {
        String path = "..//webapps//PortalCidadao/";
        File fi;
        BufferedImage imagem;
        String img = null;
        for (int i = 0; i < posts.size(); i++) {

            img = posts.get(i);
            try {
                fi = new File(path + img);
                byte[] fileContent = Files.readAllBytes(fi.toPath());
                img = encodeImage(fileContent);
                // p.setImagem(teste);
            } catch (IOException ex) {
                Logger.getLogger(PostIphone.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return img;

    }

    public static String encodeImage(byte[] imageDataString) {
        return Base64.encodeBase64String(imageDataString);
    }

    public static byte[] decodeImage(String imageDataString) {
        return Base64.decodeBase64(imageDataString);
    }
}
